package processing;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import shared.HelperBase;
import shared.SessionData;
import bean.RequestData;

public class ControllerHelper extends HelperBase {

	protected RequestData data = new RequestData();

	public ControllerHelper(HttpServletRequest request,
			HttpServletResponse response) {
		super(request, response);
		// TODO Auto-generated constructor stub
	}

	public Object getData() {
		return data;
	}

	protected void fillDataFromRequest() {
		request.getSession().setAttribute("helper", this);
		data.setUsername(request.getParameter("username"));
		data.setPassword(request.getParameter("password"));
		data.setExtras(request.getParameterValues("extras"));
		data.setGrade(request.getParameter("grade"));
		data.setComments(request.getParameter("comments"));
		data.setHappiness(request.getParameter("happiness"));
		data.setTeam(request.getParameterValues("team"));
	}

	protected void doGet() throws ServletException, IOException {
		String address = "/index.jsp";
		fillDataFromRequest();

		if (request.getParameter("confirmButton") != null) {
			address = "/Ref/Confirm.jsp";
			logger.info("Click confirm button");
		} else if (request.getParameter("successButton") != null) {
			address = "/Ref/Process.jsp";
			List<RequestData> list = new LinkedList<RequestData>();
			RequestData data1 = new RequestData("LT", "pw1");
			RequestData data2 = new RequestData("HY", "pw2");
			list.add(data1);
			list.add(data2);
			request.setAttribute("db", list);
			logger.info("Click success button");
		} else if (request.getParameter("editButton") != null) {
			address = "/index.jsp";
			logger.info("Click edit button");
		} else if (request.getParameter("returnButton") != null) {
			address = "/index.jsp";
			logger.info("Click return button");
		}

		RequestDispatcher rd = request.getRequestDispatcher(address);
		rd.forward(request, response);
	}

	protected void doPost() throws ServletException, IOException {
		doGet();
	}

	@Override
	protected void copyFromSession(Object sessionHelper) {
		// TODO Auto-generated method stub
		if (sessionHelper.getClass() == this.getClass()) {
			data = ((ControllerHelper) sessionHelper).data;
		}
	}

	@Override
	public void addHelperToSession(String name, SessionData state) {
		// TODO Auto-generated method stub
		if (SessionData.READ == state) {
			Object sessionObj = request.getSession().getAttribute(name);
			if (sessionObj != null) {
				copyFromSession(sessionObj);
			}
		}
		request.getSession().setAttribute(name, this);
	}
}
